package com.kanshu.ksgb.fastread.doudou.common.util;

import java.util.HashMap;
import java.util.Set;

import io.reactivex.Flowable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.processors.FlowableProcessor;
import io.reactivex.processors.PublishProcessor;

/**
 * 通过rxjava2实现的eventbus
 * Created by wcy on 2017\5\9 0009.
 */
public class RxBus {
    private volatile static RxBus sBus;
    private final FlowableProcessor<Object> mBus;
    private final HashMap<Class, Disposable> mDisposableHashMap;
    private RxBus() {
        mBus =  PublishProcessor.create().toSerialized();
        mDisposableHashMap = new HashMap<>();
    }
    public static RxBus getInstance() {
        if (sBus == null) {
            synchronized (RxBus.class) {
                if (sBus == null) {
                    sBus = new RxBus();
                }
            }
        }
        return sBus;
    }

    /**
     * 注册
     * @param clazz
     * @param <T>
     * @return
     */
    public <T>Flowable<T> register(Class<T> clazz) {
        Flowable<T> tFlowable = mBus.ofType(clazz);
        return tFlowable;
    }

    /**
     * 注册
     * @param clazz
     * @param consumer
     * @param <T>
     * @return
     */
    public <T>Flowable<T> register(Class<T> clazz, Consumer<T> consumer) {
        Flowable<T> tFlowable = mBus.ofType(clazz);
        Disposable disposable = tFlowable.subscribe(consumer);
        mDisposableHashMap.put(clazz, disposable);
        return tFlowable;
    }

    /**
     * 反注册
     * @param clazz
     * @param <T>
     */
    public <T> void unregister(Class<T> clazz) {
        Disposable disposable = mDisposableHashMap.get(clazz);
        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
            mDisposableHashMap.remove(clazz);
        }
    }

    /**
     * 取消所有注册
     */
    public void unregisterAll() {
        Set<Class> classSet = mDisposableHashMap.keySet();
        if (classSet != null) {
            for (Class aClass : classSet) {
                unregister(aClass);
                mDisposableHashMap.remove(aClass);
            }
        }
        mBus.onComplete();
        if (sBus != null) {
            sBus = null;
        }
    }

    public boolean hasSubscribers() {
        return mBus.hasSubscribers();
    }

    public void post(Object object) {
        mBus.onNext(object);
    }



}
